import { defineStore } from 'pinia'
import { store } from '@/store'
import { songType, songItem } from './types'
import { _songUrl, _songDetail, _lyric } from '@/service/song'

export const useSongStore = defineStore({
  id: 'music-song',
  state: (): songType => ({
    songList: JSON.parse(localStorage.getItem('songList')) ?? [],
    currentSongId:
      (localStorage.getItem('currentSongId') &&
        Number(localStorage.getItem('currentSongId'))) ??
      0,
    currentSongDetail: {
      al: {
        tns: []
      },
      alia: [],
      tns: [],
      name: ''
    },
    currentLyric: {
      lrc: null,
      lyricUser: null,
      tlyric: null,
      transUser: null
    },
    currentTime:
      (localStorage.getItem('currentTime') &&
        Number(localStorage.getItem('currentTime'))) ??
      0,
    lyricOpen: false,
    status: true, //播放状态
    volume: 50
  }),
  getters: {
    songIds: (state): songItem[] => state.songList.map((ele) => ele.id)
  },
  actions: {
    setSonglist(list: songItem[]) {
      this.songList = list
      localStorage.setItem('songList', JSON.stringify(this.songList))
      if (this.songIds.includes(this.currentSongId)) return
      this.toggleSongId(list[0].id)
      this.getSongDetail()
    },
    concatSonglist(list: songItem[]) {
      this.songList = Array.from(new Set(list.concat(this.songList)))
      localStorage.setItem('songList', JSON.stringify(this.songList))
      if (this.songIds.includes(this.currentSongId)) return
      this.toggleSongId(list[0].id)
      this.getSongDetail()
    },
    deleteSong(song: songItem) {
      // 先切换歌曲否则找不到
      if (song.id === this.currentSongId) {
        this.toggleSong('next')
      }
      const idx = this.songIds.findIndex((id: number) => id === song.id)
      this.songList.splice(idx, 1)
      localStorage.setItem('songList', JSON.stringify(this.songList))
    },
    clearSonglist() {
      this.songList = []
      localStorage.setItem('songList', JSON.stringify(this.songList))
    },
    async addSong(song: songItem) {
      // 判断是否是同一首歌
      if (this.currentSongId === song.id) return
      this.toggleSongId(song.id)
      if (!this.songIds.includes(song.id)) {
        const songDetail = await this.getSongInfo()
        this.songList.unshift(songDetail)
        localStorage.setItem('songList', JSON.stringify(this.songList))
      }
      this.getSongDetail()
    },
    async getSongDetail() {
      return new Promise((resolve) => {
        this.getSongLyric()
        const detail = this.songList.find(
          (song: songItem) => song.id === this.currentSongId
        )
        this.getSongUrl().then((res) => {
          this.currentSongDetail = Object.assign(detail, res)
          resolve(this.currentSongDetail)
        })
      })
    },
    getSongLyric() {
      return new Promise((resolve) => {
        _lyric({ id: this.currentSongId }).then((res) => {
          this.currentLyric = {
            lrc: res.lrc,
            lyricUser: res.lyricUser,
            tlyric: res.tlyric,
            transUser: res.transUser
          }
          resolve(res)
        })
      })
    },
    getSongInfo() {
      return new Promise((resolve) => {
        _songDetail({ ids: this.currentSongId }).then((res) => {
          resolve(res.songs[0])
        })
      })
    },
    getSongUrl() {
      return new Promise((resolve) => {
        _songUrl({ id: this.currentSongId }).then((res) => {
          resolve(res.data[0])
        })
      })
    },
    toggleSong(type: 'pre' | 'next') {
      const index = this.songIds.findIndex(
        (id: number) => this.currentSongId === id
      )
      let changeIndex: number
      if (type === 'next') {
        changeIndex = index < this.songIds.length - 1 ? index + 1 : 0
      } else {
        changeIndex = index === 0 ? this.songIds.length - 1 : index - 1
      }
      this.toggleSongId(this.songIds[changeIndex])
      this.getSongDetail()
    },
    toggleSongId(id: number) {
      this.currentSongId = id
      this.status = false
      localStorage.setItem('currentSongId', this.currentSongId + '')
    }
  }
})

export function useSongStoreHook() {
  return useSongStore(store)
}
